package com.tfswx.jcyw.dmzc.util;

import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.tfswx.jcyw.dmzc.service.DlxxService;
import com.tfswx.jcyw.dmzc.service.XmxxService;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

public final class ProjectUtil {

    private ProjectUtil() {
    }

    public static XmxxService selectXm(final Project project) {
        final XmxxService xmxx = XmxxService.getInstance(project).getState();
        final List<String> xmlbList = Arrays.asList("检察业务", "其他业务");
        (new DialogWrapper(true) {
            private final JComboBox<String> xmComboBox = new JComboBox<>();

            {
                this.setTitle("选择项目");
                this.init();
            }


            @Override
            protected JComponent createCenterPanel() {
                JPanel jPanel = new JPanel(new GridLayout(2, 2));
                jPanel.add(new JLabel("项目标识："));
                jPanel.add(new JLabel(project.getName()));
                jPanel.add(new JLabel("项目类型："));

                for (String s : xmlbList) {
                    this.xmComboBox.addItem(s);
                }

                this.xmComboBox.setSelectedItem(xmxx.getXmlx());
                jPanel.add(this.xmComboBox);
                return jPanel;
            }

            @Override
            protected void doOKAction() {
                Object item = this.xmComboBox.getSelectedItem();
                if (item == null) {
                    throw new NullPointerException("null cannot be cast to non-null type kotlin.String");
                }
                String selectedItem = (String) item;
                xmxx.setXmlx(selectedItem);
                super.doOKAction();
            }
        }).show();
        Notification notification = NotificationUtil.create("当前项目：" + project.getName() + "(" + xmxx.getXmlx() + ")", "代码走查-选择项目", NotificationType.INFORMATION);
        notification.notify(project);
        return xmxx;
    }


    public static String getOpenFilePath(Project project) {
        String projectBasePath = project.getBasePath();

        FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
        FileEditor selectedEditor = fileEditorManager.getSelectedEditor();

        if (selectedEditor == null) {
            throw new RuntimeException("编辑器没有打开");
        }
        VirtualFile openFile = selectedEditor.getFile();

        Path relativize = Paths.get(projectBasePath).relativize(Paths.get(openFile.getCanonicalPath()));
        return FilenameUtils.separatorsToUnix(relativize.toString());
    }

    public static void openFileInEditor(Project project, @NotNull String zcwjlj) {
        Integer startLine = null;
        Integer endLine = null;
        if (zcwjlj.contains(":")) {
            String[] split = zcwjlj.split(":");
            zcwjlj = split[0];
            if (split[1].contains("-")) {
                String[] split1 = split[1].split("-");
                startLine = Integer.parseInt(split1[0]) - 1;
                endLine = Integer.parseInt(split1[1]) - 1;
            }
        }

        File file = new File(project.getBasePath(), zcwjlj);
        if (!file.exists()) {
            Messages.showWarningDialog("文件不存在，可能已经删除或者重命名！", "警告");
            return;
        }
        VirtualFile fileByIoFile = LocalFileSystem.getInstance().findFileByIoFile(file);
        if (fileByIoFile == null) {
            Messages.showWarningDialog("文件可能不是该项目的文件！", "警告");
            return;
        }
        FileEditorManager instance = FileEditorManager.getInstance(project);
        @NotNull OpenFileDescriptor openFileDescriptor;
        if (startLine != null) {
            openFileDescriptor = new OpenFileDescriptor(project, fileByIoFile, startLine, 0);
        } else {
            openFileDescriptor = new OpenFileDescriptor(project, fileByIoFile);
        }
        Editor editor = instance.openTextEditor(openFileDescriptor, true);
        if (editor == null) {
            NotificationUtil.create("编辑器打开失败", "代码走查", NotificationType.ERROR);
            return;
        }

        if (startLine != null) {
            Document document = editor.getDocument();
            int lineStartOffset = document.getLineStartOffset(startLine);
            int lineEndOffset = document.getLineEndOffset(endLine);
            editor.getSelectionModel().setSelection(lineStartOffset, lineEndOffset);
        }

    }

    public static boolean checkLogin(Project project) {
        DlxxService dlxx = DlxxService.getInstance();
        if (StringUtils.isBlank(dlxx.getDlbm()) || StringUtils.isBlank(dlxx.getKl())) {
            NotificationUtil.showLogin(project);
            return false;
        }
        return true;
    }
}
